import { validatenull } from '@/util/validate'
import website from '@/config/website'

const keyName = website.key + '-'

/**
 * 存储localStorage
 */
export const setStore = (params = {}) => {
  let { name, content, type } = params
  window[type ? 'sessionStorage' : 'localStorage'].setItem(
    keyName + name,
    JSON.stringify({
      dataType: typeof content,
      content,
      type,
      datetime: new Date().getTime()
    })
  )
}

/**
 * 获取localStorage
 */
export const getStore = (params = {}) => {
  const { name, debug } = params
  let obj = window.sessionStorage.getItem(keyName + name) || window.localStorage.getItem(keyName + name)

  if (validatenull(obj)) return

  try {
    obj = JSON.parse(obj)
  } catch {
    return obj
  }

  if (debug) return obj

  const { dataType, content } = obj
  return dataType == 'string' || dataType == 'object'
    ? content
    : dataType == 'number'
    ? Number(content)
    : dataType == 'boolean'
    ? eval(content)
    : content
}

/**
 * 获取全部localStorage
 */
export const getAllStore = (params = {}) => {
  const { type } = params
  const storage = window[type ? 'sessionStorage' : 'localStorage']

  return storage.map((_, index) => ({
    name: storage.key(index),
    content: getStore(
      type
        ? {
            name: storage.key(index),
            type: 'session'
          }
        : { name: storage.key(index) }
    )
  }))
}

/**
 * 删除localStorage
 */
export const removeStore = (params = {}) => {
  window[params.type ? 'sessionStorage' : 'localStorage'].removeItem(keyName + params.name)
}

/**
 * 清空全部localStorage
 */
export const clearStore = (params = {}) => {
  window[params.type ? 'sessionStorage' : 'localStorage'].clear()
}
